﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Common.Unit
{
    /// <summary>
    /// UrlEncodeDecode 的摘要说明
    /// </summary>
    public static class UrlEncoder
    {
        public static string EncodeUTF8(string str)
        {
            return Encode(str, Encoding.UTF8);
        }
        public static string EncodeUnicode(string str)
        {
            return Encode(str, Encoding.Unicode);
        }
        public static string EncodeGB2312(string str)
        {
            return Encode(str, Encoding.GetEncoding("GB2312"));
        }
        public static string DecodeUTF8(string str)
        {
            return Decode(str, Encoding.UTF8);
        }
        public static string DecodeUnicode(string str)
        {
            return Decode(str, Encoding.Unicode);
        }
        public static string DecodeGB2312(string str)
        {
            return Decode(str, Encoding.GetEncoding("GB2312"));
        }
        public static string Encode(string str, Encoding encoding)
        {
            return System.Web.HttpUtility.UrlEncode(str, encoding);
        }
        public static string Decode(string str, Encoding encoding)
        {
            return System.Web.HttpUtility.UrlDecode(str, encoding);
        }
        public static string Escape(string s)
        {
            return Microsoft.JScript.GlobalObject.escape( s );
            //if (s == "") return s;
            //StringBuilder sb = new StringBuilder("");
            //byte[] byteArr = System.Text.Encoding.Unicode.GetBytes(s);
            //for (int i = 0; i < byteArr.Length - 1; i += 2)
            //{
            //    sb.Append("%u");
            //    sb.Append(byteArr[i + 1].ToString("X2"));//把字节转换为十六进制的字符串表现形式
            //    sb.Append(byteArr[i].ToString("X2"));
            //}
            //return sb.ToString();
        }
        //把JavaScript的escape()转换过去的字符串解释回来
        //方法支持汉字
        public static string UnEscape(string s)
        {
            return Microsoft.JScript.GlobalObject.unescape( s );
            //if (s == "") return s;
            //string str = s.Remove(0, 2);//删除最前面两个＂%u＂
            //if (str == "") return "";
            //string[] strArr = str.Split(new string[] { "%u" }, StringSplitOptions.None);//以子字符串＂%u＂分隔
            //byte[] byteArr = new byte[strArr.Length * 2];
            //for (int i = 0, j = 0; i < strArr.Length; i++, j += 2)
            //{
            //    byteArr[j + 1] = Convert.ToByte(strArr[i].Substring(0, 2), 16); //把十六进制形式的字串符串转换为二进制字节
            //    byteArr[j] = Convert.ToByte(strArr[i].Substring(2, 2), 16);
            //}
            //str = System.Text.Encoding.Unicode.GetString(byteArr);　//把字节转为unicode编码
            //return str;
        }

        static void test()
        {
            Console.WriteLine( UrlEncoder.EncodeUTF8( "abc蔡&壮&茂" ) );
        }
    }
}
